package com.gyc.simple.sysuser.excel.excellistener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.gyc.simple.common.util.DateUtils;
import com.gyc.simple.common.util.MD5Utils;
import com.gyc.simple.common.util.UUIDUtils;
import com.gyc.simple.sysuser.entity.base.IUser;
import com.gyc.simple.sysuser.service.SysUserService;
import com.gyc.simple.sysuser.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;

import java.util.ArrayList;
import java.util.List;
//@Scope("prototype")
//@Component
public class UserBatchListener extends AnalysisEventListener<IUser> {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserBatchListener.class);

    private SysUserService sysUserService;

    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    List<IUser> list = new ArrayList<IUser>();
    List<String> DuplicateName = new ArrayList<>();

    public UserBatchListener(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    @Override
    public void invoke(IUser iUser, AnalysisContext analysisContext) {
        iUser.setIuId(UUIDUtils.getUUID32());
        String info = iUser.getIuPassword() + DateUtils.dateToString(iUser.getIuRegistertime(), "yyyy/MM/dd HH:mm:ss");
        iUser.setIuPassword(MD5Utils.getMD5String(info));
        list.add(iUser);

        if(list.size()>=BATCH_COUNT){
            saveData(list);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData(list);
    }

    private void saveData(List<IUser> iUsers){
        try {
            //SysUserService sysUserService = ContextLoader.getCurrentWebApplicationContext().getBean(SysUserService.class);
            //sysUserService.batchAddUser(iUsers);
            DuplicateName.addAll(sysUserService.batchAddUser(iUsers));
            list.clear();
        }catch (Exception e){
            e.printStackTrace();
            list.clear();
        }
    }

    public List<String> getDuplicateName() {
        return DuplicateName;
    }
}
